package jp.dip.ysato.excitewidget;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.RemoteViews;

public class ExciteService extends IntentService {

	public ExciteService(String name) {
		super(name);
		// TODO Auto-generated constructor stub
	}
	public ExciteService() {
		super("ExciteService");
	}
	@Override
	protected void onHandleIntent(Intent arg0) {
		// TODO Auto-generated method stub
		DBHelper dbhelper = new DBHelper(this);
		SQLiteDatabase db = dbhelper.getWritableDatabase();
		Cursor cur = db.query("account", new String[]{"rowid", "user", "password"}, null, null, null, null, null);
		if(!cur.moveToFirst()) {
			db.close();
			Intent i = new Intent(getApplicationContext(), LoginActivity.class);
			i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			getApplication().startActivity(i);
			return ;
		} else {
			String user = cur.getString(cur.getColumnIndex("user"));
			String pass = cur.getString(cur.getColumnIndex("password"));
			db.close();
			Coupon coupon = new Coupon();
			CookieStore cookies;
			RemoteViews view = new RemoteViews(getPackageName(), R.layout.layout);
			TelephonyManager telmgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
			String telno = telmgr.getLine1Number();
			for(;;) {
				try {
					Log.d("ExciteWidget", "IntentService");
					cookies = coupon.getLoginCookie(user, pass);
					coupon.getinfo(cookies);

					view.setTextViewText(R.id.remain, coupon.getRemain(0));
					Pattern p = Pattern.compile("(\\d+)-(\\d+)-(\\d+)");
					String sign = (String) getText(R.string.none);
					for (int i = 0; i < 3; i++) {
						String simtel = coupon.getSIM(i).getTel();
						Matcher m = p.matcher(simtel);
						m.find();
						simtel = m.group(1) + m.group(2) + m.group(3);
						if (simtel.equals(telno)) {
							sign = (String) ((coupon.getSIM(i).isFast())?getText(R.string.on):getText(R.string.off));
							break;
						}
					}
					view.setTextViewText(R.id.fast, sign);
					break;
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				try {
					Thread.sleep(60 * 1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			ComponentName widget = new ComponentName(this, ExciteWidget.class);
			AppWidgetManager manager = AppWidgetManager.getInstance(this);
			manager.updateAppWidget(widget, view);
			Intent sv = new Intent(this, ExciteService.class);
			PendingIntent pi = PendingIntent.getService(this, 0, sv, PendingIntent.FLAG_UPDATE_CURRENT);
			AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
			alarm.setInexactRepeating(AlarmManager.RTC, System.currentTimeMillis(), AlarmManager.INTERVAL_HALF_HOUR, pi);
		}
	}

}
